package cc.imos.config;

import com.xiaoleilu.hutool.http.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.json.JacksonJsonParser;
import org.springframework.util.StopWatch;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Filter 拦截器 <br />
 * Created by asher on 2017/3/8.
 */
@Slf4j
@WebFilter(filterName = "basicFilter", urlPatterns = "/*", description = "系统过滤器")
public class BasicFilter implements Filter {

    private JacksonJsonParser jacksonJsonParser = new JacksonJsonParser();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.debug(">>>>>>>>>>>>>>>>>>>>>>> bootFilter init!");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        StopWatch watch = new StopWatch();
        watch.start();
        HttpServletRequest hsrq = (HttpServletRequest) request;
        HttpServletResponse hsrp = (HttpServletResponse) response;

        String servletPath = hsrq.getServletPath();
        String accessToken = hsrq.getHeader("accessToken");

        // String refreshToken = hsrq.getHeader("refreshToken");
        // String appKey = hsrq.getHeader("appKey");
        // String appSecret = hsrq.getHeader("appSecret");

        String clientIp = HttpUtil.getClientIP(hsrq);
        String sign = hsrq.getHeader("");

        log.debug(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        log.debug("请求地址：servletPath({})", servletPath);

        try {
//            allowCheck.doCheck(servletPath, accessToken);
            chain.doFilter(request, response);
        } catch (Throwable e) {
            log.error("Filter : {}", e.getMessage());
            log.error("Filter : {}", e);
        }

//        ObjectMapper mapper = new ObjectMapper();
//        String result = mapper.writeValueAsString(new Rest());
//        response.setCharacterEncoding("UTF-8");
//        PrintWriter out = response.getWriter();
//        out.write(result);
        watch.stop();
        log.debug("本次请求耗时 {} 毫秒！", watch.getTotalTimeMillis());
    }

    @Override
    public void destroy() {
        log.debug(">>>>>>>>>>>>>>>>>>>>>>> bootFilter destroy!");
    }
}
